import axios from 'axios'
// import store from '@/store'
import { Notification as notification } from 'element-ui'
import qs from 'qs'
import { getToken } from '@/token'
import router from '@/router'
// import { getToken } from '@/utils/auth'

axios.defaults.withCredentials = true
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// 创建 axios 实例
const axiosRequest = axios.create({
  // API 请求的默认前缀
  baseURL: '',
  timeout: 6000, // 请求超时时间
  withCredentials: true,
  // 允许在向服务器发送前，修改请求数据
  transformRequest: [
    params => {
      // console.log('paramsSerializer', params)
      return qs.stringify(params, { arrayFormat: 'indices' })
    }
  ],
  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  paramsSerializer: params => {
    return qs.stringify(params, { arrayFormat: 'indices' })
  }
})
// 请求拦截
const requestInterception = config => {
  const token = getToken()
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  config.withCredentials = true
  return config
}

// 异常拦截处理器
const errorHandler = error => {
  if (error.response) {
    if (error.response.status === 400 || error.response.status === 403) {
      notification.error({
        title: '系统提示',
        message: error.message
      })
    }

    if (error.response.status === 401) {
      notification.error({
        title: '系统提示',
        message: '您当前的会话已经结束，或者您没有当前访问权限'
      })
      // store.dispatch('user/logout')
    }
  }
  return Promise.reject(error)
}

// 请求拦截
axiosRequest.interceptors.request.use(requestInterception, errorHandler)

// 响应拦截
axiosRequest.interceptors.response.use(response => {
  // console.log(response)
  const data = response.data
  // 如果是下载文件直接返回文件流
  if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
    return response
    // eslint-disable-next-line eqeqeq
  } else if (String(data.code) === '401') {
    router.replace('/login')
    return Promise.reject(new Error(data.msg))
  } else if (!(String(data.code) === '0' || String(data.code) === '200')) {
    // 如果出错提示错误信息
    notification.error({
      title: '提示',
      message: data.msg
    })
    return Promise.reject(new Error(data.msg))
  }
  return data.data
}, errorHandler)

class AxiosMethods {
  /**
   * get请求方法
   * @param url
   * @param params
   * @returns {Promise<unknown>}
   */
  get(url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      const option = Object.assign({}, { params }, config)
      axiosRequest.get(url, option).then(
        data => {
          resolve(data)
        },
        err => {
          reject(err.message)
        }
      )
    })
  }

  /**
   * post 请求方法
   * @param url
   * @param params
   * @returns {Promise<unknown>}
   */
  post(url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axiosRequest.post(url, params, config).then(
        data => {
          resolve(data)
        },
        err => {
          reject(err.message)
        }
      )
    })
  }

  /**
   * post 请求方法
   * @param url
   * @param params
   * @returns {Promise<unknown>}
   */
  put(url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axiosRequest.put(url, params, config).then(
        data => {
          resolve(data)
        },
        err => {
          reject(err.message)
        }
      )

      // axiosRequest.put(url, params,{
      //   'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      // }).then(data => {
      //         resolve(data)
      // }, err => { console.log(err)
      //   reject(err.message)
      // }).catch((error) => {
      //   reject(error)
      // })
    })
  }

  /**
   * post 请求方法
   * @param url
   * @param params
   * @returns {Promise<unknown>}
   */
  postJson(url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axiosRequest.post(url, JSON.stringify(params), config).then(
        data => {
          resolve(data)
        },
        err => {
          reject(err.message)
        }
      )
    })
  }

  /**
   * get请求方法
   * @param url
   * @param params
   * @returns {Promise<unknown>}
   */
  delete(url, params = {}, config = {}) {
    return new Promise((resolve, reject) => {
      axiosRequest
        .delete(
          url,
          {
            params: Object.assign({}, params || {})
          },
          config
        )
        .then(
          data => {
            resolve(data)
          },
          err => {
            reject(err.message)
          }
        )
    })
  }

  axiosRequest(config = {}) {
    return new Promise((resolve, reject) => {
      axiosRequest.axiosRequest(config).then(
        data => {
          resolve(data)
        },
        err => {
          notification.error({
            message: 'Forbidden',
            description: err.message
          })
          reject(err.message)
        }
      )
    })
  }
}
const axiosMethods = new AxiosMethods()

export default axiosMethods

// 创建 axios 实例
const axios2 = axios.create({
  // API 请求的默认前缀
  baseURL: '',
  timeout: 6000, // 请求超时时间
  withCredentials: true,
  // 允许在向服务器发送前，修改请求数据
  transformRequest: [
    params => {
      // console.log('paramsSerializer', params)
      return qs.stringify(params, { arrayFormat: 'indices' })
    }
  ],
  // `paramsSerializer` 是一个负责 `params` 序列化的函数
  paramsSerializer: params => {
    return qs.stringify(params, { arrayFormat: 'indices' })
  }
})
// 请求拦截
axios2.interceptors.request.use(requestInterception, errorHandler)

// 响应拦截
axios2.interceptors.response.use(response => {
  // console.log(response)
  const data = response.data
  // 如果是下载文件直接返回文件流
  if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') {
    return response
    // eslint-disable-next-line eqeqeq
  } else if (!(String(data.code) == '0' || String(data.code) == '200')) {
    // 如果出错提示错误信息
    notification.error({
      title: '提示',
      message: data.msg
    })
    return Promise.reject(new Error(data.msg))
  }
  return data
}, errorHandler)
export { axios2 as service }
